/** 
 * File-Name:ArticleRepository.java
 *
 * Created on 2011-6-2 下午03:48:12
 * 
 * @author: Neo (neolimeng@gmail.com)
 * Software Engineering Institute, Peking University, China
 * 
 * Copyright (c) 2009, Peking University
 * 
 *
 */
package site.service.repository;

import java.sql.Connection;
import java.util.List;

import neoutil.CommonService;
import neoutil.DaoSupport;
import neoutil.Page;

import org.apache.commons.dbutils.DbUtils;
import org.apache.log4j.Logger;

import site.dao.ArticleDao;
import site.dao.UserDao;
import site.entity.Article;

/**
 * Description: 用户Article的各种存储相关操作。
 * 
 * @author: Neo (neolimeng@gmail.com) Software Engineering Institute, Peking
 *          University, China
 * @version 1.0 2011-6-2 下午03:48:12
 */
public class ArticleRepository extends CommonService {
	private static Logger log = Logger.getLogger(ArticleRepository.class);
	private String SQL_GET_BY_ID = "SELECT * FROM article WHERE id=? and entityStatus=1";
	private String SQL_GET_LATEST_ONE_BY_TYPE = "SELECT * FROM article WHERE type=? AND entityStatus=1 ORDER BY updateDate DESC";
	private String SQL_DELETE_BY_ID = "UPDATE article SET entityStatus=0 WHERE id=?";
	private String SQL_SEARCH_BY_KEYWORD = "SELECT * FROM article WHERE entityStatus=1 and title like %?%";

	public String save(Article article) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);

			articleDao.save(article);
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存Article对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			closeConnection(connection);
		}
	}

	public String update(Article article) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			return SUCCESS;
		} catch (Exception e) {
			log.error("更新Article对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public String delete(long id) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { id };
			articleDao.execute(SQL_DELETE_BY_ID, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("假删除Article对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Article get(long id) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { id };
			List<Article> articles = articleDao.find(SQL_GET_BY_ID, params);
			if (articles == null || articles.size() == 0) {
				return null;
			} else if (articles.size() > 1) {
				log.error("根据ID查询到的Article个数不唯一，为防止错误，返回null!");
				return null;
			} else {
				return articles.get(0);
			}
		} catch (Exception e) {
			log.error("根据ID取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Article getArticleByUuid(String uuid) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);

			Article article = articleDao.getByUuid(uuid);
			UserDao userDao = new UserDao(connection);
			article.setAuthor(userDao.getById(article.getAuthorId()));

			return article;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public Page<Article> getArticlesByCategoryId(final Page<Article> page,
			long categoryId) {
		Connection connection = null;

		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);
			String sql = "SELECT * FROM article WHERE categoryId=?";
			Object[] params = { categoryId };
			Page<Article> articles = articleDao.find(page, sql, params);
			return articles;
		} catch (Exception e) {
			log.error("根据Type取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	public Article getTheLatestByType(int type) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Object[] params = { type };
			List<Article> articles = articleDao.find(
					SQL_GET_LATEST_ONE_BY_TYPE, params);
			if (articles == null || articles.size() == 0) {
				return null;
			} else {
				log.info("根据ID查询到的Article个数不唯一，选取第一个!");
				Article article = articles.get(0);

				UserRepository userRepository = new UserRepository();
				article.setAuthor(userRepository.getUserById(article
						.getAuthorId()));

				return article;
			}
		} catch (Exception e) {
			log.error("按类别取得最新的Article，取得Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Page<Article> search(Page<Article> page, String query) {
		Connection connection = DaoSupport.getConnection();
		ArticleDao articleDao = new ArticleDao(connection);

		try {
			Page<Article> articles = articleDao.find(page,
					"SELECT * FROM article WHERE entityStatus=1 and title like '%"
							+ query + "%'");
			return articles;
		} catch (Exception e) {
			log.error("搜索Article对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public List<Article> getLatestArticlesByCategoryId(long categoryId,
			int topNum) {
		Connection connection = null;
		try {
			connection = DaoSupport.getConnection();
			ArticleDao articleDao = new ArticleDao(connection);

			String sql = "SELECT * FROM article WHERE categoryId=? AND entityStatus=1 ORDER BY updateDate DESC LIMIT 0,?";

			Object[] params = { categoryId, topNum };
			List<Article> articles = articleDao.find(sql, params);
			return articles;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeConnection(connection);
		}
	}

	/**
	 * Description:
	 * 
	 * @param args
	 *            void
	 */
	public static void main(String[] args) {
		Article article = new Article();
		article.setTitle("北科大校友基金会最新通知");
		article.setContent("北京科技大学校友基金会最新通知内容如下。");
		article.setAuthorId(1L);
		// article.setType(Article.NOTICE);

		ArticleRepository articleRepository = new ArticleRepository();
		// articleRepository.update(article);
		articleRepository.save(article);

		// List<Article> articles = articleRepository.getLatestArticlesByType(
		// Article.NOTICE, 3);
		// System.out.println(articles.size());

	}

}
